package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.FreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class FreemarkerServiceImpl implements FreemarkerService {

    @Autowired
    Configuration configuration;
    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    @Async//异步处理
    public void buildArticleContentPageAndToMinio(ApArticle article, String content) {
        log.info("线程名称L{}    审核通过后详情页静态化 文章:{}   内容:{]", Thread.currentThread().getName(),  article, content);

        //1.校验
        if(StringUtils.isBlank(content) || article==null || article.getId()==null){
            return;
        }

        //2.freemarker静态化
        String uploadHtmlFile=null;//详情页url路径
        Template template = null;
        try {
            template = configuration.getTemplate("article.ftl");
            Map<String,Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));//转集合对象，模版才能遍历，字符串不能用list指令遍历
            StringWriter stringWriter = new StringWriter();
            template.process(map, stringWriter);//静态化 到StringWriter流中


            //3.上传minio
            String contentHtmlSourceCode = stringWriter.toString();//详情页源代码
            InputStream is = new ByteArrayInputStream(contentHtmlSourceCode.getBytes(StandardCharsets.UTF_8));
            uploadHtmlFile = fileStorageService.uploadHtmlFile("", article.getId() + ".html", is);
            log.info("详情页上传minio后的地址:{}", uploadHtmlFile);

        } catch (Exception e) {
            log.error("详情页静态化失败，需要人工处理", e);
            return;
        }

        //4.更新ap_article表static_url字段
        article.setStaticUrl(uploadHtmlFile);
        apArticleMapper.updateById(article);


        //5.发送消息到kafka  构建索引
        createArticleIndex(article, content);

    }

    @Autowired
    KafkaTemplate<String, String>  kafkaTemplate;
    /**
     * 将文章信息发送到kafka   用于索引到es
     * @param article  文章
     * @param content   文章内容
     *
     * 发消息1、导依赖   2、配置kafka信息   3、利用kafkaTemplate发消息
     */
    private void createArticleIndex(ApArticle article, String content) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(article, vo);
        vo.setContent(content);
        String jsonString = JSON.toJSONString(vo);
        log.info("发送消息到kafka  用于构建索引    {}", jsonString);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, jsonString);
    }
}
